import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;

/**
 * 
 */

/**
 * @description
 * 
 * @author vihuynh, k7ho
 * 
 */
public class Lookup {
	final static String MSG_USAGE = "Usage: %s indexfile\n";
	private String[] trimedWords;
	private Hashtable<String, Hashtable<String, Integer>> hashTbl;

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		if (args.length < 1) {
			System.out.printf(MSG_USAGE, Lookup.class.getName());
			return;
		} else {
			Lookup lookup = new Lookup();
			try {
				lookup.ReadFile(args[0]);

				Scanner in = new Scanner(System.in);
				System.out
						.println("Enter keyword query (blank line to exit the program): ");
				String temp = in.nextLine();
				while (!temp.equals("")) {
					lookup.prompt(temp);
					System.out
							.println("Enter keyword query (blank line to exit the program): ");
					temp = in.nextLine();
				}

				System.out.println("Okay, bye.");
				//System.out.println("Okay, goodbye. -_-'");
				// System.out.println(" (^-^) <(''<) (>'')> t(''t) Q(''Q) ");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				//e.printStackTrace();
				System.out.printf("Couldn't open %s for reading exiting.\n", args[0]);
			}
		}

	}

	private void prompt(String inStr) {

		trimedWords = inStr.split(" ");

		Hashtable<String, Hashtable<String, Integer>> tbl = (Hashtable<String, Hashtable<String, Integer>>) hashTbl;
		LinkedList<Hashtable<String, Integer>> multList = new LinkedList<Hashtable<String, Integer>>();
		
		for (String str : trimedWords) {

			int count = 0;
			System.out.printf("\"%s\" stems to --> \"%s\":", str,
					(str = Keyword.makeKeyword(str)));
			if(str.equals("")) {
				System.out.println(" ignoring.");
				continue;
			}
			if (hashTbl.containsKey(str)) {
				count = hashTbl.get(str).size();

				System.out.printf("  found in %d web pages.\n", count);			
//				System.out.printf("RESULTS: %d documents match all query "
//						+ "keywords.\n", count);
				
//				System.out.println("Here they are, sorted:");
				// for(Hashtable <String, Hashtable<String, Integer>> blah :
				// hashTbl.get(str))
				
				
				//FOR MULTIPLE WORDS DATA STRUCTURE
				multList.add(hashTbl.get(str));
//				
//				Object[] ary = hashTbl.get(str).entrySet().toArray();	
//				Comparator myCompa = new MyComparator();
//				
//				Arrays.sort(ary,(Comparator) myCompa);
//				
//				for(int i=0;i<ary.length;++i) {
//					System.out.print(((Map.Entry)ary[i]).getKey());
//					System.out.println(": score " + ((Map.Entry)ary[i]).getValue());
//				}
//
			} else {
				//empty hashtable for non-found word
				multList.add(new Hashtable<String, Integer>());	
			
				System.out.printf("  found in %d web pages.\n", count);			
//				System.out.printf("RESULTS: %d documents match all query "
//						+ "keywords.\n", count);
			}
		}
		
		//FIND PAGES WITH ALL WORDS
		Hashtable<String, Integer> urlList = new Hashtable<String, Integer>();
		boolean flag=false;
		for(Hashtable<String, Integer> tempHash : multList){
			if(!flag) {
				urlList = new Hashtable<String, Integer>(tempHash);
				flag = true;
			}
			else {	
				Hashtable<String, Integer> tempURLList = new Hashtable<String, Integer>(urlList);
				Set<String> tempList = tempURLList.keySet();
				//synchronized (tempList) {
				for(String tempString : tempList){
					if(tempHash.containsKey(tempString)) {
						urlList.put(tempString, urlList.get(tempString) 
								+ tempHash.get(tempString));
					}
					else {
						urlList.remove(tempString);
					}
				}
				//}
			}
		}
		
		Object[] ary = urlList.entrySet().toArray();	
		Comparator myCompa = new MyComparator();
		
		Arrays.sort(ary,(Comparator) myCompa);
		
		System.out.printf("RESULTS: %d documents match all query "
				+ "keywords.\n", urlList.size());
		
		for(int i=0;i<ary.length;++i) {
			System.out.print(((Map.Entry)ary[i]).getKey());
			System.out.println(": score " + ((Map.Entry)ary[i]).getValue());
		}
		
//		//print out pages with all words
//		System.out.println("HERE IS THE LIST OF PAGES CONTAINING ALL WORDS: ");
//		Set<String> temp = urlList.keySet();
//		for(String tempString : temp) {
//			System.out.println(tempString + " (" + urlList.get(tempString) + ")");
//		}
	}

	@SuppressWarnings("unchecked")
	public void ReadFile(String filePath) throws IOException,
			ClassNotFoundException {
		FileInputStream fis = new FileInputStream(filePath);
		BufferedInputStream bis = new BufferedInputStream(fis);
		ObjectInputStream ois = new ObjectInputStream(bis);

		hashTbl = (Hashtable<String, Hashtable<String, Integer>>) ois
				.readObject();

		System.out.println("Reading index file " + filePath + "... Contains "
				+ hashTbl.size() + " keywords.");
	}

}

class MyComparator implements Comparator{

	@Override
	public int compare(Object a, Object b) {
		 if( ((Integer)((Map.Entry)a).getValue()).intValue() < ((Integer)((Map.Entry)b).getValue()).intValue() ){
             return(1);
     }else if( ((Integer)((Map.Entry)a).getValue()).intValue() > ((Integer)((Map.Entry)b).getValue()).intValue() ){
             return(-1);
     }else{
             return(0);
     }
	}
	
}